<?php
/**
 * Created by PhpStorm.
 * User: cabbage
 * Date: 2019/3/21
 * Time: 2:20 PM
 */

namespace app\common\command;

use fast\Redis;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Session;

class Websocket extends Command
{
    protected $fd;
    protected $server;
    protected $redis;
    protected function configure()
    {
        $this->setName('socket')
            ->setDescription('webSocket ');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->server = new \Swoole\WebSocket\Server("0.0.0.0", 9501);

        $this->server->on('open', function (\Swoole\WebSocket\Server $server, $request) {
//            echo "server: handshake success with fd{$request->fd}\n";
            $this->redis = Redis::getRedis();
        });

        $this->server->on('message', function (\Swoole\WebSocket\Server $server, $frame) {
            $data=json_decode($frame->data,true);
            switch ($data['event']){
                case 'login':
                    $redis = Redis::getRedis();
                    $cookie=$data['cookie'];
                    $number= $redis->sIsMember('fd:'.$data['uuid'],$cookie);
                    if ($number){
                        $number='ing';
                    }else{
                        $number='out';
                    }
                    echo "redis{$number},admin_ids:{$data['admin']}\n";
                    $message = [
                        'event'=>'login',
                        'status' =>200 ,
                        'content'=>$number
                    ];
                    break;

            }
            $message=[];
            echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
            $server->push($frame->fd, json_encode($message));
        });

        $this->server->on('close', function ($ser, $fd) {
            echo "client {$fd} closed\n";
        });

        $this->server->on('request', function ($request, $response) {
            // 接收http请求从get获取message参数的值，给用户推送
            // $this->server->connections 遍历所有websocket连接用户的fd，给所有用户推送
            echo $request->get['type'];
            foreach ($this->server->connections as $fd) {
                // 需要先判断是否是正确的websocket连接，否则有可能会push失败
                if ($this->server->isEstablished($fd)) {
                    $this->server->push($fd, $request->get['message']);
                }
            }
        });
        $this->server->start();
    }
}